package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserLoginService {
    @Override
    public ResponseResult login(LoginDto dto) {

        // 1.检验参数
        if (dto.getEquipmentId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "嗯？你不对劲，没设备你怎么进来的？");
        }

        if (StringUtils.isNotEmpty(dto.getPhone()) && StringUtils.isNotEmpty(dto.getPassword())) {
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone())
                    .eq(ApUser::getStatus, 0));
            if (apUser == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "请检查手机号");
            }
            String password = apUser.getPassword();
            String newPassword = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            if (password.equals(newPassword)) {
                apUser.setPassword("");
                apUser.setSalt("");
                Map<String, Object> map = new HashMap<>();
                map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                map.put("user", apUser);
                return ResponseResult.okResult(map);
            } else {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "手机号或者密码错误");
            }

        }
            Map<String ,Object> map = new HashMap();
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
    }
}
